<template>
    <div class="head">
        <h1 class="title">日程管理</h1>
    </div>
    <div class='demo-app'>
        <div class='demo-app-main'>
            <FullCalendar class='demo-app-calendar' :options='calendarOptions'>
                <template v-slot:eventContent='arg'>
                    <b>{{ arg.timeText }}</b>
                    <i>{{ arg.event.title }}</i>
                </template>
            </FullCalendar>
        </div>
    </div>
</template>

<script>
import { defineComponent } from 'vue'
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import moment from 'moment'
import axios from 'axios'

let eventGuid = 0

export function createEventId() {
    return String(eventGuid++)
}

export default defineComponent({
    components: {
        FullCalendar,
    },
    data() {
        return {
            name: this.$store.state.userName,
            id: this.$store.state.id,
            calendarOptions: {
                plugins: [
                    dayGridPlugin,
                    interactionPlugin // needed for dateClick
                ],
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth'
                },
                initialView: 'dayGridMonth',
                events: [],
                editable: true,
                selectable: true,
                selectMirror: true,
                dayMaxEvents: true,
                weekends: true,
                select: this.handleDateSelect,
                eventClick: this.handleEventClick,
                eventsSet: this.handleEvents,
            },
            currentEvents: [],
            patients: Array(7).fill(0),
            Information: [],
            initFinish: false,
            hasGet: false,
        }
    },
    created() {
        this.getBookInformation()
    },
    methods: {
        async getBookInformation() {
            try {
                const res = await axios.get('http://localhost:8085/api/appointment/getByDoctorId', {
                    params: {
                        doctorId: this.id
                    }
                });
                this.Information = res.data;
                this.hasGet = true;
                this.initCalendarEvents();
            } catch (error) {
                console.error('Error fetching appointment information:', error);
            }
        },
        initCalendarEvents() {
            if (this.hasGet && !this.initFinish) {
                this.initFinish = true;
                const currentDate = new Date();
                const currentYear = currentDate.getFullYear();
                const currentMonth = currentDate.getMonth() + 1;
                const currentDay = currentDate.getDate();

                this.Information.forEach(info => {
                    const time = info.appointmentTime;
                    const year = Number(time.slice(0, 4));
                    const month = Number(time.slice(5, 7));
                    const day = Number(time.slice(8, 10));
                    if (currentYear === year && currentMonth === month) {
                        const dayDiff = day - currentDay;
                        if (dayDiff < 7 && dayDiff >= 0) {
                            this.patients[dayDiff]++;
                        }
                    }
                });

                for (let i = 0; i < 7; i++) {
                    const event = {
                        id: createEventId(),
                        title: `已预约人数: ${this.patients[i]}`,
                        start: moment().add(i, 'days').format('YYYY-MM-DD'),
                        overlap: true,
                        editable: true
                    };
                    this.calendarOptions.events.push(event);
                }
            }
        },
        handleDateSelect(selectInfo) {
            const title = prompt('Please enter a new title for your event');
            const calendarApi = selectInfo.view.calendar;
            calendarApi.unselect(); // clear date selection

            if (title) {
                calendarApi.addEvent({
                    id: createEventId(),
                    title,
                    start: selectInfo.startStr,
                    end: selectInfo.endStr,
                    allDay: selectInfo.allDay
                });
            }
        },
        handleEvents(events) {
            this.currentEvents = events;
        },
        handleEventClick(clickInfo) {
            if (confirm(`Are you sure you want to delete the event '${clickInfo.event.title}'`)) {
                clickInfo.event.remove();
            }
        }
    }
});
</script>

<style lang='css'>
h2 {
    margin: 0;
    font-size: 16px;
}

ul {
    margin: 0;
    padding: 0 0 0 1.5em;
}

li {
    margin: 1.5em 0;
    padding: 0;
}

b {
    /* used for event dates/times */
    margin-right: 3px;
}

.demo-app {
    display: flex;
    min-height: 100%;
    font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
    font-size: 14px;
}

.demo-app-sidebar {
    width: 300px;
    line-height: 1.5;
    background: #eaf9ff;
    border-right: 1px solid #d3e2e8;
}

.demo-app-sidebar-section {
    padding: 2em;
}

.demo-app-main {
    flex-grow: 1;
    padding: 3em;
}

.fc {
    /* the calendar root */
    max-width: 1100px;
    margin: 0 auto;
}
</style>
